import React, { FC, useState, MouseEvent } from 'react'
import { useDispatch } from 'react-redux'
import styles from './EditCanvas.module.scss'
import { Spin } from 'antd'
import classNames from 'classnames'

import useCanvaskeyPress from '../../../hooks/useCanvasKeyPress'
import useGetComponentsInfo from '../../../hooks/useGetComponentInfo'
import { getComponentConfByType } from '../../../components/QuestionComponents'
import { ComponentInfoType, changeSelectedId } from '../../../store/componentsReducer'

// 临时引入
// import QuestionTitle from '../../../components/QuestionComponents/QuestionTitle/Components'
// import QuestionInput from '../../../components/QuestionComponents/QuestionInput/Components'

type PropsType = {
  loading: boolean
}
function getComponent(component: ComponentInfoType) {
  const { type, props } = component
  const componentConfig = getComponentConfByType(type)
  if (componentConfig == null) return null

  const { Component } = componentConfig
  return <Component {...props} />
}

const EditCanvas: FC<PropsType> = ({ loading }) => {
  const { componentList, selectedId } = useGetComponentsInfo()
  const dispatch = useDispatch()

  function handleClick(event: MouseEvent, id: string) {
    event.stopPropagation()
    console.log(id)
    dispatch(changeSelectedId(id))
  }

  useCanvaskeyPress()

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '24px' }}>
        <Spin />
      </div>
    )
  }
  return (
    <div className={styles.canvas}>
      {componentList
        .filter(c => !c.isHidden)
        .map(c => {
          const { fe_id, isLocked } = c
          const wrapperDefaultClassName = styles['components-wrapper']
          const selectedClassName = styles.selected
          const lockedClassName = styles.locked
          const wrapperClassName = classNames({
            [wrapperDefaultClassName]: true,
            [selectedClassName]: fe_id === selectedId,
            [lockedClassName]: isLocked
          })
          return (
            <div key={fe_id} className={wrapperClassName} onClick={e => handleClick(e, fe_id)}>
              <div className={styles.component}>{getComponent(c)}</div>
            </div>
          )
        })}
      {/* <div className={styles['components-wrapper']}>
        <div className={styles.component}>
          <QuestionTitle />
        </div>
      </div>
      <div className={styles['components-wrapper']}>
        <div className={styles.component}>
          <QuestionInput />
        </div>
      </div> */}
    </div>
  )
}

export default EditCanvas
